<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }
        
        .header {
            background: white;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .back-btn {
            font-size: 18px;
            color: #333;
            text-decoration: none;
        }
        
        .title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }
        
        .header-icons {
            display: flex;
            gap: 15px;
            color: #666;
        }
        
        .container {
            max-width: 400px;
            margin: 0 auto;
            background: white;
            min-height: 100vh;
        }
        
        .form-section {
            padding: 20px;
        }
        
        .user-type-section {
            margin-bottom: 30px;
        }
        
        .user-type-buttons {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .user-type-btn {
            display: flex;
            align-items: center;
            padding: 20px;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            background: white;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .user-type-btn.selected {
            border-color: #007AFF;
            background: #f0f8ff;
        }
        
        .user-type-icon {
            width: 24px;
            height: 24px;
            margin-right: 15px;
            background: #007AFF;
            border-radius: 4px;
        }
        
        .user-type-text {
            font-size: 16px;
            font-weight: 500;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            color: #333;
            font-weight: 500;
        }
        
        .input-group {
            position: relative;
        }
        
        .form-input {
            width: 100%;
            padding: 15px 45px 15px 15px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            background: white;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #007AFF;
        }
        
        .input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            width: 20px;
            height: 20px;
            color: #666;
        }
        
        
        .radio-group {
            display: flex;
            gap: 20px;
        }
        
        .radio-item {
            display: flex;
            align-items: center;
            cursor: pointer;
        }
        
        .radio-input {
            margin-right: 8px;
            width: 18px;
            height: 18px;
        }
        
        .upload-area {
            border: 2px dashed #e0e0e0;
            border-radius: 12px;
            padding: 40px 20px;
            text-align: center;
            background: #fafafa;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .upload-area:hover {
            border-color: #007AFF;
            background: #f0f8ff;
        }
        
        .upload-icon {
            width: 40px;
            height: 40px;
            margin: 0 auto 15px;
            background: #007AFF;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
        }
        
        .upload-text {
            font-size: 16px;
            color: #333;
            margin-bottom: 8px;
        }
        
        .upload-hint {
            font-size: 12px;
            color: #666;
        }
        
        .certificate-section {
            margin-top: 20px;
        }
        
        .certificate-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .certificate-count {
            font-size: 14px;
            color: #666;
        }
        
        .add-certificate {
            border: 2px dashed #e0e0e0;
            border-radius: 12px;
            padding: 30px 20px;
            text-align: center;
            background: #fafafa;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .add-certificate:hover {
            border-color: #007AFF;
            background: #f0f8ff;
        }
        
        .add-icon {
            width: 40px;
            height: 40px;
            margin: 0 auto 15px;
            background: #007AFF;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
        }
        
        .agreement {
            padding: 20px;
            text-align: center;
            font-size: 14px;
            color: #666;
            line-height: 1.5;
        }
        
        .agreement-link {
            color: #007AFF;
            text-decoration: none;
        }
        
        .register-btn {
            width: 100%;
            padding: 18px;
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin: 20px 0;
        }
        
        .register-btn:hover {
            background: #0056b3;
        }
        
        .customer-service {
            text-align: center;
            padding: 20px;
            font-size: 14px;
            color: #666;
        }
        
        .service-link {
            color: #007AFF;
            text-decoration: none;
        }
        
        .hidden {
            display: none;
        }
        
        .pilot-only {
            display: block;
        }
        
        .organization-only {
            display: none;
        }
        
        .user-type-organization .pilot-only {
            display: none;
        }
        
        .user-type-organization .organization-only {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <a href="#" class="back-btn">‹</a>
            <div class="title">注册</div>
            <div class="header-icons">
                <span>⋯</span>
                <span>⚙</span>
            </div>
        </div>
        
        <div class="form-section">
            <form id="registerForm">
                <!-- 用户类型选择 -->
                <div class="user-type-section">
                    <div class="user-type-buttons">
                        <div class="user-type-btn selected" data-type="1">
                            <div class="user-type-icon"></div>
                            <div class="user-type-text">飞手注册</div>
                        </div>
                        <div class="user-type-btn" data-type="2">
                            <div class="user-type-icon"></div>
                            <div class="user-type-text">组织注册</div>
                        </div>
                    </div>
                </div>

                <!-- 手机号码 -->
                <div class="form-group">
                    <label class="form-label">手机号码</label>
                    <div class="input-group">
                        <input type="tel" name="phone" class="form-input" placeholder="请输入手机号码" required>
                    </div>
                </div>

                <!-- 密码 -->
                <div class="form-group">
                    <label class="form-label">密码</label>
                    <div class="input-group">
                        <input type="password" name="password" class="form-input" placeholder="请设置密码 (6-16位字符)" required>
                    </div>
                </div>

                <!-- 确认密码 -->
                <div class="form-group">
                    <label class="form-label">确认密码</label>
                    <div class="input-group">
                        <input type="password" name="confirmPassword" class="form-input" placeholder="请再次输入密码" required>
                    </div>
                </div>

                <!-- 姓名 -->
                <div class="form-group pilot-only">
                    <label class="form-label">姓名</label>
                    <div class="input-group">
                        <input type="text" id="realName" name="realName" class="form-input" placeholder="请输入真实姓名 (用于证书认证)" required>
                    </div>
                </div>

                <!-- 组织名称 -->
                <div class="form-group organization-only">
                    <label class="form-label">组织名称</label>
                    <div class="input-group">
                        <input type="text" id="orgName" name="orgName" class="form-input" placeholder="请输入公司名称 (用于证书认证)" required>
                    </div>
                </div>

                <!-- 性别 -->
                <div class="form-group pilot-only">
                    <label class="form-label">性别</label>
                    <div class="radio-group">
                        <label class="radio-item">
                            <input type="radio" name="gender" value="male" class="radio-input" checked>
                            <span>男</span>
                        </label>
                        <label class="radio-item">
                            <input type="radio" name="gender" value="female" class="radio-input">
                            <span>女</span>
                        </label>
                    </div>
                </div>


                <!-- 年龄 -->
                <div class="form-group pilot-only">
                    <label class="form-label">年龄</label>
                    <div class="input-group">
                        <input type="number" id="age" name="age" class="form-input" placeholder="请输入年龄" min="16" max="80" required>
                    </div>
                </div>

                <!-- 飞行年限 -->
                <div class="form-group pilot-only">
                    <label class="form-label">飞行年限</label>
                    <div class="input-group">
                        <input type="number" id="flightYears" name="flightYears" class="form-input" placeholder="请输入飞行年限（年）" min="0" max="60" required>
                    </div>
                </div>

                <!-- 身份证照片 -->
                <div class="form-group pilot-only">
                    <label class="form-label">身份证照片</label>
                    
                    <div class="form-group">
                        <label class="form-label">身份证正面</label>
                        <div class="upload-area" onclick="document.getElementById('idCardFront').click()">
                            <div class="upload-icon">↑</div>
                            <div class="upload-text">上传正面照片</div>
                            <div class="upload-hint">请上传本人身份证正面照片,确保清晰可辨</div>
                        </div>
                        <input type="file" id="idCardFront" name="idCardFront" accept="image/*,.webp" style="display: none;">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">身份证反面</label>
                        <div class="upload-area" onclick="document.getElementById('idCardBack').click()">
                            <div class="upload-icon">↑</div>
                            <div class="upload-text">上传反面照片</div>
                            <div class="upload-hint">请上传本人身份证反面照片,确保清晰可辨</div>
                        </div>
                        <input type="file" id="idCardBack" name="idCardBack" accept="image/*,.webp" style="display: none;">
                    </div>
                </div>

                <!-- 保险信息 -->
                <div class="form-group pilot-only">
                    <label class="form-label">保险信息</label>
                    
                    <div class="certificate-section">
                        <div class="certificate-header">
                            <label class="form-label">保单 (三者)</label>
                            <span class="certificate-count" id="insuranceCount">(0/5)</span>
                        </div>
                        
                        <div class="add-certificate" onclick="document.getElementById('insurance').click()">
                            <div class="add-icon">+</div>
                            <div class="upload-text">添加保单 (pdf或jpg)</div>
                            <div class="upload-hint">请上传三者保险单文件,可上传多个保单(最多5个)</div>
                        </div>
                        <input type="file" id="insurance" name="insurance" accept="image/*,.webp,application/pdf" multiple style="display: none;">
                    </div>
                </div>

                <!-- 地区 -->
                <div class="form-group pilot-only">
                    <label class="form-label">地区</label>
                    <div class="input-group">
                        <input type="text" id="address" name="address" class="form-input" placeholder="请选择地区" required>
                    </div>
                </div>

                <!-- 个人证书/资质证明 -->
                <div class="certificate-section pilot-only">
                    <div class="certificate-header">
                        <label class="form-label">个人证书/资质证明</label>
                        <span class="certificate-count" id="certificateCount">(0/5)</span>
                    </div>
                    
                    <div class="add-certificate" onclick="document.getElementById('certificate').click()">
                        <div class="add-icon">+</div>
                        <div class="upload-text">添加证书 (pdf或jpg)</div>
                        <div class="upload-hint">请上传至少一个飞手证书,可上传多个证书(最多5个)</div>
                    </div>
                    <input type="file" id="certificate" name="certificate" accept="image/*,.webp,application/pdf" multiple style="display: none;">
                </div>

                <!-- 营业执照上传 -->
                <div class="certificate-section organization-only">
                    <div class="certificate-header">
                        <label class="form-label">个人证书/资质证明</label>
                        <span class="certificate-count" id="licenseCount">(0/1)</span>
                    </div>
                    
                    <div class="add-certificate" onclick="document.getElementById('license').click()">
                        <div class="add-icon">+</div>
                        <div class="upload-text">上传营业执照 (pdf或jpg)</div>
                        <div class="upload-hint">请上传营业执照文件</div>
                    </div>
                    <input type="file" id="license" name="license" accept="image/*,.webp,application/pdf" style="display: none;">
                </div>

            </form>
        </div>
        
        <!-- 用户协议 -->
        <div class="agreement">
            注册即代表您同意<a href="#" class="agreement-link">《用户协议》</a>和<a href="#" class="agreement-link">《隐私政策》</a>
        </div>
        
        <!-- 注册按钮 -->
        <div class="form-section">
            <button type="submit" form="registerForm" class="register-btn">注册</button>
        </div>
        
        <!-- 客服联系 -->
        <div class="customer-service">
            如遇到注册问题,请联系<a href="#" class="service-link">客服</a>
        </div>
    </div>

    <script>
        // 页面初始化 - 检查默认用户类型
        document.addEventListener('DOMContentLoaded', function() {
            // 检查是否有默认选中的组织注册按钮
            const organizationBtn = document.querySelector('.user-type-btn[data-type="2"]');
            const pilotBtn = document.querySelector('.user-type-btn[data-type="1"]');
            
            if (organizationBtn && organizationBtn.classList.contains('selected')) {
                // 如果默认选中组织注册，移除飞手字段的必填属性
                document.getElementById('realName').removeAttribute('required');
                document.getElementById('age').removeAttribute('required');
                document.getElementById('flightYears').removeAttribute('required');
                document.getElementById('address').removeAttribute('required');
                // 确保组织名称是必填的
                document.getElementById('orgName').setAttribute('required', 'required');
            } else {
                // 默认情况（飞手注册），移除组织名称的必填属性
                document.getElementById('orgName').removeAttribute('required');
            }
        });

        // 用户类型选择
        document.querySelectorAll('.user-type-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.user-type-btn').forEach(b => b.classList.remove('selected'));
                this.classList.add('selected');
                
                // 切换表单字段显示
                const userType = this.dataset.type;
                const container = document.querySelector('.container');
                
                if (userType === '2') {
                    // 组织方注册
                    container.classList.add('user-type-organization');
                    // 移除飞手专用字段的必填属性
                    document.getElementById('realName').removeAttribute('required');
                    document.getElementById('age').removeAttribute('required');
                    document.getElementById('flightYears').removeAttribute('required');
                    document.getElementById('address').removeAttribute('required');
                    // 添加组织名称的必填属性
                    document.getElementById('orgName').setAttribute('required', 'required');
                } else {
                    // 飞手注册
                    container.classList.remove('user-type-organization');
                    // 恢复飞手专用字段的必填属性
                    document.getElementById('realName').setAttribute('required', 'required');
                    document.getElementById('age').setAttribute('required', 'required');
                    document.getElementById('flightYears').setAttribute('required', 'required');
                    document.getElementById('address').setAttribute('required', 'required');
                    // 移除组织名称的必填属性
                    document.getElementById('orgName').removeAttribute('required');
                }
            });
        });

        // 文件上传预览
        function handleFileUpload(input, previewArea) {
            input.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        previewArea.innerHTML = `
                            <div class="upload-icon">✓</div>
                            <div class="upload-text">${file.name}</div>
                            <div class="upload-hint">文件已上传</div>
                        `;
                    };
                    reader.readAsDataURL(file);
                }
            });
        }

        // 初始化文件上传
        handleFileUpload(document.getElementById('idCardFront'), document.querySelector('#idCardFront').previousElementSibling);
        handleFileUpload(document.getElementById('idCardBack'), document.querySelector('#idCardBack').previousElementSibling);
        
        // 保险单文件存储
        let insuranceFiles = [];
        
        // 保险单计数更新
        document.getElementById('insurance').addEventListener('change', function(e) {
            const newFiles = Array.from(e.target.files);
            console.log('新选择的文件数量:', newFiles.length);
            
            // 添加新文件到现有列表
            newFiles.forEach(file => {
                if (insuranceFiles.length < 5) {
                    insuranceFiles.push(file);
                    console.log('添加文件:', file.name);
                } else {
                    console.log('已达到最大文件数量限制(5个)');
                }
            });
            
            console.log('当前保险单文件总数:', insuranceFiles.length);
            console.log('保险单文件列表:', insuranceFiles.map(f => f.name));
            
            // 更新计数显示
            const countElement = document.getElementById('insuranceCount');
            if (countElement) {
                countElement.textContent = `(${insuranceFiles.length}/5)`;
                console.log('更新计数为:', `(${insuranceFiles.length}/5)`);
            }
            
            // 清空input，允许下次选择
            e.target.value = '';
        });

        // 证书文件存储
        let certificateFiles = [];
        
        // 证书计数更新
        document.getElementById('certificate').addEventListener('change', function(e) {
            const newFiles = Array.from(e.target.files);
            console.log('新选择的证书文件数量:', newFiles.length);
            
            // 添加新文件到现有列表
            newFiles.forEach(file => {
                if (certificateFiles.length < 5) {
                    certificateFiles.push(file);
                    console.log('添加证书文件:', file.name);
                } else {
                    console.log('已达到最大证书文件数量限制(5个)');
                }
            });
            
            console.log('当前证书文件总数:', certificateFiles.length);
            console.log('证书文件列表:', certificateFiles.map(f => f.name));
            
            // 更新计数显示
            const countElement = document.getElementById('certificateCount');
            console.log('证书计数元素:', countElement);
            console.log('证书计数元素内容:', countElement ? countElement.textContent : 'null');
            if (countElement) {
                countElement.textContent = `(${certificateFiles.length}/5)`;
                console.log('更新证书计数为:', `(${certificateFiles.length}/5)`);
                console.log('更新后元素内容:', countElement.textContent);
            } else {
                console.error('找不到证书计数元素');
            }
            
            // 清空input，允许下次选择
            e.target.value = '';
        });

        // 营业执照文件存储
        let licenseFiles = [];
        
        // 营业执照计数更新
        document.getElementById('license').addEventListener('change', function(e) {
            const newFiles = Array.from(e.target.files);
            console.log('新选择的营业执照文件数量:', newFiles.length);
            
            // 营业执照只能上传一个文件
            if (newFiles.length > 0) {
                licenseFiles = [newFiles[0]]; // 只保留第一个文件
                console.log('添加营业执照文件:', newFiles[0].name);
            }
            
            console.log('当前营业执照文件总数:', licenseFiles.length);
            console.log('营业执照文件列表:', licenseFiles.map(f => f.name));
            
            // 更新计数显示
            const countElement = document.getElementById('licenseCount');
            if (countElement) {
                countElement.textContent = `(${licenseFiles.length}/1)`;
                console.log('更新营业执照计数为:', `(${licenseFiles.length}/1)`);
            }
            
            // 清空input，允许下次选择
            e.target.value = '';
        });

        // 表单提交
        document.getElementById('registerForm').addEventListener('submit', function(e) {
            e.preventDefault();
            submitRegisterForm();
        });

        // 完整的注册功能
        async function submitRegisterForm() {
            try {
                // 显示加载状态
                const submitBtn = document.querySelector('.register-btn');
                const originalText = submitBtn.textContent;
                submitBtn.textContent = '注册中...';
                submitBtn.disabled = true;

                // 收集表单数据
                const formData = collectFormData();
                
                // 验证表单
                if (!validateFormData(formData)) {
                    throw new Error('表单验证失败');
                }

                // 上传照片
                const uploadedPhotos = await uploadPhotos(formData);
                console.log('上传的照片数据:', uploadedPhotos);
                
                // 合并照片数据到表单数据
                Object.assign(formData, uploadedPhotos);
                console.log('合并后的表单数据:', formData);

                // 提交注册
                const result = await submitRegistration(formData);
                
                if (result.code === 200) {
                    showSuccess('注册成功，请等待审核');
                    setTimeout(() => {
                        window.location.href = '/login';
                    }, 2000);
                } else {
                    throw new Error(result.msg || '注册失败');
                }

            } catch (error) {
                showError(error.message || '注册失败，请重试');
            } finally {
                // 恢复按钮状态
                const submitBtn = document.querySelector('.register-btn');
                submitBtn.textContent = '注册';
                submitBtn.disabled = false;
            }
        }

        // 收集表单数据
        function collectFormData() {
            const form = document.getElementById('registerForm');
            const formData = new FormData(form);
            const data = {};

            // 用户类型
            const userTypeBtn = document.querySelector('.user-type-btn.selected');
            data.userType = userTypeBtn ? userTypeBtn.dataset.type : '1';

            // 基本字段
            data.phone = document.querySelector('input[type="tel"]').value;
            data.password = document.querySelector('input[type="password"]').value;
            
            // 根据用户类型收集不同的姓名字段
            if (data.userType === '1') {
                // 飞手注册
                data.realName = document.querySelector('input[placeholder*="真实姓名"]').value;
                data.age = parseInt(document.querySelector('input[placeholder*="年龄"]').value);
                data.flightYears = parseInt(document.querySelector('input[placeholder*="飞行年限"]').value);
            } else {
                // 组织注册
                data.realName = document.querySelector('input[placeholder*="公司名称"]').value;
                data.orgName = data.realName; // 组织名称
            }
            
            // 性别
            const genderRadio = document.querySelector('input[name="gender"]:checked');
            data.gender = genderRadio ? genderRadio.value : 'male';

            // 地区
            data.region = document.querySelector('input[placeholder*="地区"]').value;

            // DTO要求的必填字段（使用默认值）
            data.userName = data.phone; // 使用手机号作为用户名
            data.confirmPassword = data.password; // 确认密码
            data.email = data.phone + '@example.com'; // 临时邮箱
            data.address = data.region; // 使用地区作为地址
            data.emergencyContact = data.realName; // 使用真实姓名作为紧急联系人
            data.emergencyPhone = data.phone; // 使用手机号作为紧急联系人电话
            data.explorationInfo = 'temp_exploration'; // 临时探险信息
            data.qualification = 'temp_qualification'; // 临时资质信息
            data.captcha = '1234'; // 临时验证码
            data.uuid = generateUUID(); // 生成UUID

            // 照片字段（这些会在uploadPhotos中更新）
            if (data.userType === '1') {
                // 飞手注册特有字段
                data.explorationInfo = 'temp_exploration';
                data.qualification = 'temp_qualification';
            }

            return data;
        }

        // 生成UUID
        function generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                const r = Math.random() * 16 | 0;
                const v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }

        // 验证表单数据
        function validateFormData(data) {
            // 通用验证
            if (!data.phone) {
                showError('请输入手机号码');
                return false;
            }
            if (!data.password) {
                showError('请输入密码');
                return false;
            }
            
            if (data.userType === '1') {
                // 飞手注册验证
                if (!data.realName) {
                    showError('请输入真实姓名');
                    return false;
                }
                if (!data.age || data.age < 16 || data.age > 80) {
                    showError('请输入有效年龄（16-80岁）');
                    return false;
                }
                if (data.flightYears < 0 || data.flightYears > 60) {
                    showError('请输入有效飞行年限（0-60年）');
                    return false;
                }
                
                // 检查飞手必填文件
                const idCardFront = document.getElementById('idCardFront');
                const idCardBack = document.getElementById('idCardBack');
                const insurance = document.getElementById('insurance');
                const certificate = document.getElementById('certificate');
                
                if (!idCardFront.files[0]) {
                    showError('请上传身份证正面照片');
                    return false;
                }
                if (!idCardBack.files[0]) {
                    showError('请上传身份证反面照片');
                    return false;
                }
                if (insuranceFiles.length === 0) {
                    showError('请上传保单（技术证明）');
                    return false;
                }
                if (certificateFiles.length === 0) {
                    showError('请上传个人证书');
                    return false;
                }
                
            } else {
                // 组织注册验证
                if (!data.orgName) {
                    showError('请输入组织名称');
                    return false;
                }
                
                // 检查组织必填文件
                const license = document.getElementById('license');
                if (licenseFiles.length === 0) {
                    showError('请上传资质证明（营业执照）');
                    return false;
                }
            }
            
            return true;
        }

        // 上传照片
        async function uploadPhotos(formData) {
            const uploadedPhotos = {};
            
            // 只有飞手注册时才上传飞手特有照片
            if (formData.userType === '1') {
                // 上传身份证正面（必填）
                const idCardFront = document.getElementById('idCardFront');
                const result1 = await uploadPhoto(idCardFront.files[0], '/drone/photo/upload/idcard/front');
                if (result1.code === 200) {
                    uploadedPhotos.idCardFront = result1.msg;
                    console.log('身份证正面照片URL:', result1.msg);
                } else {
                    throw new Error('身份证正面照片上传失败: ' + result1.msg);
                }

                // 上传身份证反面（必填）
                const idCardBack = document.getElementById('idCardBack');
                const result2 = await uploadPhoto(idCardBack.files[0], '/drone/photo/upload/idcard/back');
                if (result2.code === 200) {
                    uploadedPhotos.idCardBack = result2.msg;
                    console.log('身份证反面照片URL:', result2.msg);
                } else {
                    throw new Error('身份证反面照片上传失败: ' + result2.msg);
                }

                // 上传保险单（保单照片作为技能证明，必填）
                uploadedPhotos.skills = [];
                for (let i = 0; i < insuranceFiles.length; i++) {
                    const result = await uploadPhoto(insuranceFiles[i], '/drone/photo/upload/certificate');
                    if (result.code === 200) {
                        uploadedPhotos.skills.push(result.msg);
                    } else {
                        throw new Error(`保险单${i+1}上传失败: ${result.msg}`);
                    }
                }

                // 上传证书（必填）
                uploadedPhotos.certificates = [];
                for (let i = 0; i < certificateFiles.length; i++) {
                    const result = await uploadPhoto(certificateFiles[i], '/drone/photo/upload/certificate');
                    if (result.code === 200) {
                        uploadedPhotos.certificates.push(result.msg);
                    } else {
                        throw new Error(`证书${i+1}上传失败: ${result.msg}`);
                    }
                }

                // 设置探险信息和资质信息的默认值
                uploadedPhotos.explorationInfo = 'default_exploration.jpg';
                uploadedPhotos.qualification = 'default_qualification.jpg';
            } else {
                // 组织注册时上传营业执照（作为证书，必填）
                uploadedPhotos.certificates = [];
                const result = await uploadPhoto(licenseFiles[0], '/drone/photo/upload/certificate');
                if (result.code === 200) {
                    uploadedPhotos.certificates.push(result.msg);
                    uploadedPhotos.licenseImage = result.msg; // 同时设置licenseImage字段
                    console.log('营业执照URL:', result.msg);
                } else {
                    throw new Error('营业执照上传失败: ' + result.msg);
                }
            }

            return uploadedPhotos;
        }

        // 上传单个照片
        async function uploadPhoto(file, url) {
            const formData = new FormData();
            formData.append('file', file);

            console.log('上传照片:', file.name, '到:', url);

            const response = await fetch(url, {
                method: 'POST',
                body: formData
            });

            const result = await response.json();
            console.log('上传结果:', result);
            
            return result;
        }

        // 提交注册
        async function submitRegistration(data) {
            let url = '/drone/register/pilot'; // 默认飞手注册
            
            if (data.userType === '2') {
                // 组织注册，构建组织注册数据
                const orgData = {
                    userName: data.userName || data.phone, // 使用手机号作为用户名
                    password: data.password,
                    confirmPassword: data.confirmPassword,
                    phone: data.phone,
                    email: data.email,
                    orgName: data.orgName,
                    licenseImage: data.licenseImage,
                    captcha: data.captcha,
                    uuid: data.uuid
                };
                url = '/drone/register/organization';
                return await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(orgData)
                }).then(response => response.json());
            } else {
                // 飞手注册
                return await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                }).then(response => response.json());
            }
        }

        // 显示错误信息
        function showError(message) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = message;
            errorDiv.style.cssText = 'position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: #ff4757; color: white; padding: 15px 25px; border-radius: 8px; z-index: 1000; font-size: 14px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);';
            
            document.body.appendChild(errorDiv);
            
            setTimeout(() => {
                errorDiv.remove();
            }, 3000);
        }

        // 显示成功信息
        function showSuccess(message) {
            const successDiv = document.createElement('div');
            successDiv.className = 'success-message';
            successDiv.textContent = message;
            successDiv.style.cssText = 'position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: #2ed573; color: white; padding: 15px 25px; border-radius: 8px; z-index: 1000; font-size: 14px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);';
            
            document.body.appendChild(successDiv);
            
            setTimeout(() => {
                successDiv.remove();
            }, 3000);
        }
    </script>
</body>
</html>


